import { useQuery } from "@apollo/client";
import { connectFactory, useAppContext } from "@/utils/contextFactory";
import { GET_USER_INFO } from "@/graphql/user";
import { IUser } from "@/utils/types";
import { useLocation, useNavigate } from "react-router-dom";

const KEY = "userInfo";
const DEFAULT_VALUE = {};
export const useUserContext = () => useAppContext(KEY);
export const connect = connectFactory(KEY, DEFAULT_VALUE);
export const useGetUser = () => {
  const { setStore } = useUserContext();
  const location = useLocation();
  const nav = useNavigate();
  const { loading, refetch } = useQuery<{ getUserInfo: IUser }>(GET_USER_INFO, {
    onCompleted: (data) => {
      if (data.getUserInfo) {
        const { id, tel, name, desc, avatar } = data.getUserInfo;
        setStore({
          id,
          tel,
          desc,
          name,
          avatar,
          refetchHandler: refetch,
        });
        if (location.pathname.startsWith("/login")) {
          nav("/");
        }
        return;
      }
      setStore({ refetchHandler: refetch });
      // 如果不在登录页面，但是目前没有登录，直接跳转到登录
      if (location.pathname !== "/login") {
        nav(`/login?originUrl=${location.pathname}`);
      }
    },
    onError: () => {
      setStore({ refetchHandler: refetch });
      if (location.pathname !== "/login") {
        nav(`/login?originUrl=${location.pathname}`);
      }
    },
  });
  return {
    loading,
    refetch,
  };
};
